const Mock = require('mockjs')
const { param2Obj } = require('./utils')

const user = require('./sys') // 系统管理模块 mock
const a = require('./a')
const b = require('./b')
const structureAudit = require('./structure-audit') // 体系审核模块 mock
const basicInfo = require('./basic-info') // 信息维护模块 mock
const autoJudge = require('./auto-judge') // 等级自动评定模块 mock
const matters = require('./matters') // 信息互通模块 mock
const logistics = require('./logistics') // 监督检查整改模块 mock
const energyManage = require('./energy-manage') // 能耗管理模块 mock
const shipMaterials = require('./ship-materials') // 库存供应模块 mock

const mocks = [...user, ...a, ...b, ...structureAudit, ...basicInfo, ...autoJudge, ...matters, ...logistics, ...energyManage, ...shipMaterials]

function mockXHR() {
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function (options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

module.exports = { mockXHR }
